import {Component} from 'angular2/core';
import {UserService} from '../services/user.service';
import {TaskService} from '../services/task.service';
import {User} from '../models/user';
import {Router} from 'angular2/router';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import { TaskInfo } from '../models/taskInfo';
import {ShareTask} from '../models/sharedtask';
declare var $:any;


@Component({
  selector: 'my-task',
  templateUrl: 'app/components/my-task.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class MyTaskInfo {
  private tasks: TaskInfo[];
  private user:User;
  private users:User[];
 
  constructor (
    private router: Router,
    private userService: UserService,
    private taskService:TaskService
  ) {
    this.userService.getUserByName(localStorage.getItem("currentUserName")).subscribe(
      user => {
        this.user = JSON.parse(JSON.parse(JSON.stringify(user))._body);
        this.userService.getSharedUser(this.user).subscribe(u=>{
          this.users=JSON.parse(JSON.parse(JSON.stringify(u))._body);
        });
        this.taskService.getTasksByUser(this.user).subscribe(
          tasks =>{
            
            this.tasks=JSON.parse(JSON.parse(JSON.stringify(tasks))._body);
            console.log(this.tasks)
          
          } 
         
        ),
        error => console.log(error)
        console.log(this.tasks);
      }
    ),
    error => console.log(error)
  };

  selectCheckbox(check:boolean,value:string){    
    if(check){
      
    }
  }
  onShared(){
    if(this.tasks.filter(_ => _.selected).length==0){
      alert("Please select a task.");
      return;
     }
    $('.ui.modal').modal('show')

  }
  onSharedTask(){
    let shareTasks:ShareTask[]=[];
     
    this.users.filter(_ => _.selected).forEach(u=> {
      
      this.tasks.filter(_ => _.selected).forEach(_ => {
        let shareTask:ShareTask =new ShareTask();
        shareTask.FromUserId=this.user.userId;
        shareTask.ToUserId=u.userId;
        shareTask.TaskInfoId=_.taskId;
        shareTasks.push(shareTask);
       });
     });
     this.taskService.sharedTasks(shareTasks).subscribe(
       r=>{console.log("111")}
     ),
     error => console.log(error)
  }
  onSelect(task: TaskInfo) {
    this.router.navigate(['UpdateTaskInfo', {id: task.taskId}]);
  }
 
}
